package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Override
    public boolean remove(Long id) {
        //1.根据categoryId 去菜单表查询，有没有这个分类的菜品
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        //select count(*) from dish where category_id=?
        dishQueryWrapper.select("count(*) as count");//设定查询投影，查询什么字段
        dishQueryWrapper.eq("category_id",id);
        //设置Map集合
        Map<String, Object> dishServiceMap = dishService.getMap(dishQueryWrapper);
        Long dishcount = (Long) dishServiceMap.get("count");
        log.info("根据category去菜单表查询，查到的菜品数量为:{}",dishcount);
        //有就不删
        if (dishcount > 0){
            log.info("此菜单有菜品，不能删除!!!");
            //抛出异常
            throw new CustomException("此菜单有菜品，不能删除!!!");
        }
        //2.根据categoryId 去套餐表查询，有没有这个分类的菜品
        QueryWrapper<Setmeal> sertmealQueryWrapper = new QueryWrapper<>();
        //select count(*) from dish where category_id=?
        sertmealQueryWrapper.select("count(*) as count");//设定查询投影，查询什么字段
        sertmealQueryWrapper.eq("category_id",id);
        //设置Map集合
        Map<String, Object> setmealServiceMap = setmealService.getMap(sertmealQueryWrapper);
        Long setmealcount = (Long) setmealServiceMap.get("count");
        log.info("根据category去套餐表查询，查到的套餐数量为:{}",setmealcount);
        //有就不删
        if (setmealcount > 0){
            log.info("此分类有套餐，不能删除!!!");
            //抛出异常
            throw new CustomException("此分类有套餐，不能删除!!!");
        }
        //3.删除分类
        super.removeById(id);
        return true;
    }
}
